package com.labichaoka.chaoka.ui.home.fragment.home;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseFragment;
import com.labichaoka.chaoka.base.GlobalParams;
import com.labichaoka.chaoka.entity.BaseResponse;
import com.labichaoka.chaoka.entity.CreditCardResponse;
import com.labichaoka.chaoka.entity.HomeInitResponse;
import com.labichaoka.chaoka.entity.VerifyInfoListResponse;
import com.labichaoka.chaoka.ui.account.LoginActivity;
import com.labichaoka.chaoka.ui.bank.bind.BankBindActivity;
import com.labichaoka.chaoka.ui.baseinfo.information.InformationAuthenticationActivity;
import com.labichaoka.chaoka.ui.baseinfo.real.RealInfoActivity;
import com.labichaoka.chaoka.ui.credit.CalculateActivity;
import com.labichaoka.chaoka.ui.fetch.FetchMoneyActivity;
import com.labichaoka.chaoka.ui.home.adapter.ZixunAdapter;
import com.labichaoka.chaoka.ui.record.BorrowRecordActivity;
import com.labichaoka.chaoka.ui.web.WebViewActivity;
import com.labichaoka.chaoka.utils.DetectionUtil;
import com.labichaoka.chaoka.utils.GlideImageLoader;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;
import com.labichaoka.chaoka.utils.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class HomeFragment extends BaseFragment implements HomeFragmentView, OnBannerListener {
    @BindView(R.id.back_layout)
    RelativeLayout back;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.question_icon)
    TextView questionIcon;
    @BindView(R.id.txt_warning)
    TextView warning;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.calculate)
    TextView calculate;
    @BindView(R.id.order_desc)
    TextView orderDesc;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.img_layout)
    LinearLayout imgLayout;

    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.quote)
    TextView quote;
    @BindView(R.id.quote_txt)
    TextView quoteTxt;
    @BindView(R.id.repay_txt)
    TextView repayTxt;
    @BindView(R.id.repay)
    TextView repay;
    @BindView(R.id.overdue_layout)
    LinearLayout overdueLayout;
    @BindView(R.id.overdue_text)
    TextView overdueTxt;
    @BindView(R.id.zixun_list)
    RecyclerView zixunList;

    private HomeFragmentPresenter presenter;

    private List<String> images = new ArrayList<>();
    private Dialog dialog;
    private String status;
    private String oldUserFlage;
    private HomeInitResponse mData;
    private String creditStatus;

    @Override
    protected int initLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        back.setVisibility(View.GONE);
        questionIcon.setTypeface(iconfont);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        zixunList.setLayoutManager(linearLayoutManager);

        zixunList.setFocusable(false);
    }

    @Override
    protected void initData() {
        presenter = new HomeFragmentPresenterImpl(this, new HomeFragmentInteractorImpl());
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
    }

    @OnClick({R.id.question_icon, R.id.calculate, R.id.order_desc, R.id.fetch_layout, R.id.repay_layout})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.question_icon:
                showNoticeDialog();
                break;
            case R.id.fetch_layout:
                if (TextUtils.isEmpty(status)) {
                    ToastUtils.show("获取参数错误，请稍后重试!");
                    return;
                }
                if (status.equals("0")) {
                    gotoActivity(mContext, LoginActivity.class, null);
                } else if (status.equals("1") || status.equals("2") || status.equals("3") || status.equals("5")) {
                    ToastUtils.show("请先完成额度计算!");
                } else if (status.equals("4")) {
                    ToastUtils.show("额度计算中，请稍后再试!");
                } else {
                    gotoActivity(mContext, FetchMoneyActivity.class, null);
                }

                break;
            case R.id.calculate:
                if (TextUtils.isEmpty(status)) {
                    ToastUtils.show("服务器异常，请稍后重试!");
                    return;
                }
                switch (status) {
                    case "0":
                        //未登录
                        gotoActivity(mContext, LoginActivity.class, null);
                        break;
                    case "1":
                        //资料未完善
                        if (!oldUserFlage.equals("1")) {
//                            presenter.creditCardSwitch();
                            presenter.getVerifyInfoList();
                        } else {
                            showCLDialog();
                        }
                        break;
                    case "5":
                        ToastUtils.show("您的信用等级不足，过段时间后再来尝试吧！");
                        //激活未通过
                        break;
                    case "6":
                        //已激活，未借款
                        gotoActivity(mContext, FetchMoneyActivity.class, null);
                        break;
                }
                break;
            case R.id.order_desc:
                gotoActivity(mContext, BorrowRecordActivity.class, null);
                break;
            case R.id.repay_layout:
                if (TextUtils.isEmpty(status)) {
                    ToastUtils.show("获取参数错误，请稍后重试!");
                    return;
                }
                if (status.equals("0")) {
                    gotoActivity(mContext, LoginActivity.class, null);
                } else if (status.equals("1") || status.equals("2") || status.equals("3") || status.equals("5")) {
                    ToastUtils.show("请先完成额度计算!");
                } else if (status.equals("4")) {
                    ToastUtils.show("额度计算中，请稍后再试!");
                } else {
                    gotoActivity(mContext, BorrowRecordActivity.class, null);
                }

                break;

        }
    }

    private void showNoticeDialog() {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.home_notice_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        TextView ok = v.findViewById(R.id.ok);
        TextView tip = v.findViewById(R.id.tip);
        LinearLayout tip_unLogin = v.findViewById(R.id.tip_unLogin);
        LinearLayout tip_login = v.findViewById(R.id.tip_login);

        if (TextUtils.isEmpty(status)) {
            return;
        }
        if (status.equals("0") || status.equals("1")) {
            tip_unLogin.setVisibility(View.VISIBLE);
            tip_login.setVisibility(View.GONE);
        } else {
            tip_unLogin.setVisibility(View.GONE);
            tip_login.setVisibility(View.VISIBLE);

            if (status.equals("2")) {
                tip.setText("您只需要等待大约1分钟就可以提现专属额度");
            } else if (status.equals("3")) {
                tip.setText("马上去激活，可立即提现");
            } else if (status.equals("4")) {
                tip.setText("专属额度激活中，我们会尽快与您取得联系");
            } else if (status.equals("5")) {
                tip.setText("您的信用等级不足，过段时间后再来尝试吧！");
            } else if (status.equals("6")) {
                tip.setText("马上借款，畅想超卡信用生活");
            } else if (status.equals("7")) {
                tip.setText("剩余额度=总额度-已提现金额");
            }
        }

        ok.setOnClickListener((view) -> {
            dialog.dismiss();
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);

        dialog.show();

    }


    private void showAdDialog(String url, String jumpUrl) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.home_ad_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        ImageView ig = v.findViewById(R.id.img_close);
        ImageView img_ad = v.findViewById(R.id.img_ad);
        Glide.with(mContext).load(url).into(img_ad);
        ig.setOnClickListener((view) -> {
            dialog.dismiss();
        });
        img_ad.setOnClickListener((view) -> {
            dialog.dismiss();
            //打开h5链接
            Bundle bundle = new Bundle();
            bundle.putString("type", "8");
            bundle.putString("url", jumpUrl);
            gotoActivity(mContext, WebViewActivity.class, bundle);
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);

        dialog.show();

    }

    private void showCLDialog() {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_cl, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        TextView ok = v.findViewById(R.id.ok);

        ok.setOnClickListener((view) -> {
            presenter.clearAuthInfo();
            dialog.dismiss();
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);

        dialog.show();

    }

    private void showVerifyOperateDialog() {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_verify_operate, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        TextView ok = v.findViewById(R.id.ok);

        ok.setOnClickListener((view) -> {
            presenter.resetUserStatus();
            dialog.dismiss();
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);

        dialog.show();
    }


    @Override
    public void showProgress() {
        showLoadingProgress();
    }

    @Override
    public void hideProgress() {
        hideLoadingPregress();
    }

    @Override
    public void showMessage(String str) {
        ToastUtils.show(str);
    }

    @Override
    public void setData(HomeInitResponse response) {
        if (response.getData() == null) {
            ToastUtils.show("获取数据异常，请稍后重试!");
            return;
        }
        mData = response;
        status = response.getData().getUser().getStatus();
        String sevenDayPay = response.getData().getUser().getWaittingPaied();
        String overdueDay = response.getData().getUser().getOverdueDay();
        String totalVal = response.getData().getUser().getTotalQuata();
        if (TextUtils.isEmpty(status) || TextUtils.isEmpty(totalVal)) {
            ToastUtils.show("获取数据异常,请稍后重试!");
            return;
        }
        if (!status.equals("0")) {
            oldUserFlage = response.getData().getOldUserFlage();
            if (!TextUtils.isEmpty(oldUserFlage)) {
                if (oldUserFlage.equals("1")) {
                    //存量用户
                    showCLDialog();
                }

            }

        }

        String quatoFlag = response.getData().getQuatoFlag();
//        if (TextUtils.isEmpty(quatoFlag)){
//            ToastUtils.show("获取数据异常，请稍候重试！");
//            return;
//        }
        if (!TextUtils.isEmpty(quatoFlag)&&quatoFlag.equals("1")) {
            showVerifyOperateDialog();
        }

        switch (status) {
            case "0":
                //未登录
                total.setText(DetectionUtil.addComma(totalVal));
                topTitle.setText("最高可借(元)");
                calculate.setVisibility(View.VISIBLE);
                warning.setVisibility(View.GONE);
                imgLayout.setVisibility(View.GONE);
                SharedPreferencesManager.getInstance().putString("token", "");
                break;
            case "1":
                //资料未完善
                total.setText(DetectionUtil.addComma(totalVal));
                total.setVisibility(View.VISIBLE);
                topTitle.setText("最高可借(元)");
                calculate.setVisibility(View.VISIBLE);
                warning.setVisibility(View.VISIBLE);
                imgLayout.setVisibility(View.GONE);
                warning.setText(response.getData().getUser().getWarning());
                break;
            case "2":
                //正在计算专属额度
                total.setText(DetectionUtil.addComma(totalVal));
                imgLayout.setVisibility(View.VISIBLE);
                total.setVisibility(View.GONE);
                warning.setVisibility(View.GONE);
                calculate.setVisibility(View.GONE);
                topTitle.setText("正在计算您的专属额度");
                break;
            case "3":
                //计算完专属额度，未激活
                total.setText(DetectionUtil.addComma(totalVal));
                warning.setVisibility(View.GONE);
                calculate.setVisibility(View.VISIBLE);
                imgLayout.setVisibility(View.GONE);
                calculate.setText("去激活");
                topTitle.setText("我的专属额度(元)");
                break;
            case "4":
                //激活中
                total.setText(DetectionUtil.addComma(totalVal));
                imgLayout.setVisibility(View.VISIBLE);
                img.setImageResource(R.mipmap.activing);
                total.setVisibility(View.VISIBLE);
                warning.setVisibility(View.GONE);
                calculate.setVisibility(View.GONE);
                topTitle.setText("正在激活您的专属额度");
                break;
            case "5":
                topTitle.setText("我的专属额度(元)");
                total.setText(DetectionUtil.addComma(totalVal));
                calculate.setVisibility(View.VISIBLE);
                calculate.setText("马上借款");
                warning.setVisibility(View.GONE);
                imgLayout.setVisibility(View.GONE);
                //激活未通过
                break;
            case "6":
                //已激活，未借款
                total.setText(DetectionUtil.addComma(totalVal));
                topTitle.setText("我的专属额度(元)");
                calculate.setText("马上借款");
                warning.setVisibility(View.GONE);
                calculate.setVisibility(View.VISIBLE);
                imgLayout.setVisibility(View.GONE);
                break;
            case "7":
                //有订单
                topTitle.setText("剩余额度(元)");
                String avaiQuota = response.getData().getUser().getAvailQuota();
                if (TextUtils.isEmpty(avaiQuota)) {
                    ToastUtils.show("获取数据异常");
                    return;
                }
                total.setText(DetectionUtil.addComma(avaiQuota));
                calculate.setVisibility(View.GONE);
                warning.setVisibility(View.VISIBLE);
                imgLayout.setVisibility(View.GONE);
                warning.setText("总额度(元) " + DetectionUtil.addComma(totalVal));
                orderDesc.setVisibility(View.VISIBLE);
                String orderStatus = response.getData().getUser().getOrderStatus();
                if (!TextUtils.isEmpty(orderStatus)) {
                    orderDesc.setText(Html.fromHtml(orderStatus));
                }

                break;
        }
        SharedPreferencesManager.getInstance().putString("status", response.getData().getUser().getStatus());

        boolean adIfShow = response.getData().isAdIfShow();
        if (adIfShow) {
            showAdDialog(response.getData().getAppAdImgUrl(), response.getData().getAdJumpUrl());
        }

        if (status.equals("0")) {
            quote.setText("借款");
            quoteTxt.setText("快速到账");
            repay.setText("还款");
            repayTxt.setText("按月计息");
        } else {
            quote.setText("借款");
            quoteTxt.setText("生活/学习/旅游");
            if (TextUtils.isEmpty(sevenDayPay) || TextUtils.isEmpty(overdueDay)) {
                ToastUtils.show("获取数据异常,请稍后重试!");
                return;
            }

            if (sevenDayPay.equals("0")) {
                repayTxt.setText("暂无");
            } else {
                repayTxt.setText(sevenDayPay);
            }

            repay.setText("近7日待还金额(元)");

            if (!overdueDay.equals("0")) {
                overdueLayout.setVisibility(View.VISIBLE);
                overdueTxt.setText("逾期第" + overdueDay + "天");
                //repayTxt.setText(overdueDay);
                repayTxt.setTextColor(getResources().getColor(R.color.font_ff4340));
            }

        }

        ZixunAdapter adapter = new ZixunAdapter(response.getData().getNews(), mContext);
        zixunList.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString("type", "8");
            bundle.putString("url", response.getData().getNews().get(position).getAppJumpUrl());
            gotoActivity(mContext, WebViewActivity.class, bundle);
        });

        images.clear();
        if (response.getData().getCarousel() != null) {
            int count = response.getData().getCarousel().size();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    images.add(response.getData().getCarousel().get(i).getAppPicUrl());
                }
            }
        }
//简单使用
        banner.setImages(images)
                .setImageLoader(new GlideImageLoader())
                .setOnBannerListener(this)
                .start();
        banner.setBannerAnimation(Transformer.Default);
        banner.setDelayTime(4000);

    }

    @Override
    public void getVerifyInfoListCallback(VerifyInfoListResponse response) {
        if (response.getData() == null) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }
        String realNameAuthState = response.getData().getRealNameAuthState();
        String bankCardAuthState = response.getData().getBankCardAuthState();
        String operatorAuthState = response.getData().getOperatorAuthState();
        String perInfoAuthState = response.getData().getPerInfoAuthState();
        String creditCardState = response.getData().getCreditCardState();

//        if (TextUtils.isEmpty(realNameAuthState) || TextUtils.isEmpty(bankCardAuthState) ||
//                TextUtils.isEmpty(operatorAuthState) || TextUtils.isEmpty(perInfoAuthState) || TextUtils.isEmpty(creditCardState)) {
//            ToastUtils.show("获取数据异常，请稍后重试！");
//            return;
//        }
//        if (realNameAuthState.equals("0")) {
//            gotoActivity(mContext, RealInfoActivity.class, null);
//            return;
//        }
//        if (bankCardAuthState.equals("0")) {
//            Bundle bundle = new Bundle();
//            bundle.putInt("type", GlobalParams.BIND_BANK_CARD);
//            gotoActivity(mContext, BankBindActivity.class, bundle);
//            return;
//        }
//        if (creditStatus.equals("01")&&creditCardState.equals("0")) {
//            gotoActivity(mContext, InformationAuthenticationActivity.class, null);
//            return;
//        }
//        if (perInfoAuthState.equals("0")) {
//            gotoActivity(mContext, InformationAuthenticationActivity.class, null);
//            return;
//        }
//
//        if (creditStatus.equals("01")) {
//            if (operatorAuthState.equals("1") && perInfoAuthState.equals("1") &&
//                    bankCardAuthState.equals("1") && realNameAuthState.equals("1") && creditCardState.equals("1")) {
//                gotoActivity(mContext, CalculateActivity.class, null);
//            }
//        } else {
//            if (operatorAuthState.equals("1") && perInfoAuthState.equals("1") &&
//                    bankCardAuthState.equals("1") && realNameAuthState.equals("1")) {
//                gotoActivity(mContext, CalculateActivity.class, null);
//            }
//        }

        if (TextUtils.isEmpty(realNameAuthState) || TextUtils.isEmpty(bankCardAuthState) || TextUtils.isEmpty(operatorAuthState) || TextUtils.isEmpty(perInfoAuthState) || TextUtils.isEmpty(creditCardState)) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }
        if (realNameAuthState.equals("0")){
            gotoActivity(mContext,RealInfoActivity.class,null);
        }else if(bankCardAuthState.equals("0")){
            Bundle bundle=new Bundle();
            bundle.putInt("type",GlobalParams.BIND_BANK_CARD);
            gotoActivity(mContext,BankBindActivity.class,bundle);
        }else if(operatorAuthState.equals("0")||perInfoAuthState.equals("0")||creditCardState.equals("3")){
            gotoActivity(mContext,InformationAuthenticationActivity.class,null);
        }else if (operatorAuthState.equals("1")&&perInfoAuthState.equals("1")&&bankCardAuthState.equals("1")&&realNameAuthState.equals("1")){
            gotoActivity(mContext,CalculateActivity.class,null);
        }

    }

    @Override
    public void clearAuthInfo(BaseResponse response) {
        presenter.getVerifyInfoList();
    }

    @Override
    public void resetUserStatusCallback(BaseResponse response) {
        presenter.getVerifyInfoList();
    }

    @Override
    public void creditCardSwitchCallback(CreditCardResponse response) {
        if (response.getData() == null) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }
        creditStatus = response.getData().getStatus();


        presenter.getVerifyInfoList();
    }


    @Override
    public void OnBannerClick(int position) {
        if (mData == null || mData.getData() == null) {
            return;
        }
        if (mData.getData().getCarousel().size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString("type", "8");
            bundle.putString("url", mData.getData().getCarousel().get(position).getAppJumpUrl());
            gotoActivity(mContext, WebViewActivity.class, bundle);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.init();
    }
}
